﻿import { SingleText } from '/plugins/lgform/singletext.js'
import { Textarea } from '/plugins/lgform/textarea.js'
import { IdNumber } from '/plugins/lgform/idNumber.js'
import { Address } from '/plugins/lgform/address.js'
import { Email } from '/plugins/lgform/email.js'
import { Link } from '/plugins/lgform/link.js'
import { Number } from '/plugins/lgform/number.js'
import { Phone } from '/plugins/lgform/phone.js'
import { Radio } from '/plugins/lgform/radio.js'
import { Checkbox } from '/plugins/lgform/checkBox.js'
import { CheckBlock } from '/plugins/lgform/checkBlock.js'
import { Select } from '/plugins/lgform/select.js'
import { MultipleSelect } from '/plugins/lgform/multipleSelect.js'
import { Date } from '/plugins/lgform/date.js'
import { DateRange } from '/plugins/lgform/daterange.js'
import { Files } from '/plugins/lgform/files.js'
import { Range } from '/plugins/lgform/range.js'
import { Switch } from '/plugins/lgform/switch.js'
import { Accept } from '/plugins/lgform/accept.js'
import { SmsCode } from '/plugins/lgform/smsCode.js'
import { Tag } from '/plugins/lgform/tag.js'
import { Group } from '/plugins/lgform/group.js'
import { Color } from '/plugins/lgform/color.js'
import { Image } from '/plugins/lgform/image.js'
import { Info } from '/plugins/lgform/info.js'
import { form } from '/plugins/lgform/form.js'


const freeForm = {
    types: {
        SingleText: SingleText,
        Textarea: Textarea,
        IdNumber: IdNumber,
        Address: Address,
        Email: Email,
        Link: Link,
        Number: Number,
        Phone: Phone,
        Radio: Radio,
        Checkbox: Checkbox,
        CheckBlock: CheckBlock,
        Select: Select,
        MultipleSelect: MultipleSelect,
        Date: Date,
        DateRange: DateRange,
        Files: Files,
        Range: Range,
        Switch: Switch,
        Accept: Accept,
        SmsCode: SmsCode,
        Tag: Tag,
        Group: Group,
        Color: Color,
        Image: Image,
        Info: Info,
    },
    //给VUE实例注册所有表单组件
    regComponent: function (app) {
        for (let key in this.types) {
            var compt = this.types[key].component;
            app.component(compt.name, compt.data);
        }
        app.component(form.component.name, form.component.data)
    },
    getComponent: function (key) {
        for (let _key in this.types) {
            if (_key.toLowerCase() == key.toLowerCase()) {
                return this.types[_key];
            }
        }
        return null;
    },
    //通过表单项类型名称获取一个类型对像
    newType: function (typeName, data = {}) {
        var c = this.getComponent(typeName);
        if (c) {
            var obj = {
                "TypeName": typeName,
                "Data": new c.model(data)
            }
            return obj;
        } else {
            return null;
        }
    },
    //将表单配置数据转为字符串用于后端存储
    toString: function (items) {
        var _items = lg.obj.copy(items);
        for (let i in _items) {
            _items[i].Data = JSON.stringify(_items[i].Data)
        }
        return JSON.stringify(_items)
    },
    //将后端返回的表单配置数据转换为表单实体集合
    toJson: function (jsonStr) {
        var _items = lg.convert.toJson(jsonStr, []);
        if (_items.length > 0) {
            for (let i in _items) {
                var c = this.getComponent(_items[i].TypeName); 
                if (c) {
                    _items[i].Data = new c.model(JSON.parse(_items[i].Data))
                } else {
                    console.log(_items[i].TypeName+"无法识别!")
                    return false;
                }
            }
        }
        return _items;
    },
    toCamel: function (str) {
        return str.slice(0, 1).toLowerCase() + str.slice(1)
    },
    //将object类型表单数据转换为表单实体集合
    toModel: function (items) {
        if (items.length > 0) {
            for (let i in items) {
                var c = this.getComponent(items[i].TypeName);
                if (c) {
                    items[i].Data = new c.model(items[i].Data)
                } else {
                    console.log(items[i].TypeName + "无法识别!")
                    return false;
                }
            }
        }
        return items;
    },
    //通过数据(json)还原表单配置数据源
    toFormData: function (items, data) {
        var res = [];
        if (typeof items == "string") {
            items = this.toJson(items);
        }
        if (typeof data == "string") {
            data = JSON.parse(data);
        }
        for (let i in items) {
            var type = items[i].Data;
            if (!type.NullValue && data[type.Name] != undefined) {
                if (type.setValue) {
                    type.setValue(data);
                } else {
                    type.Value = data[type.Name]
                }
                if (type.Value == "lg-no-render") {
                    type.IsRender = false;
                    type.Value = "";
                } else {
                    type.IsRender = true;
                }
                res.push(items[i]);
            }
        }
        return res;
    },
    copyItems: function (items) {
        var arry = [];
        for (let i in items) {
            var c = this.getComponent(items[i].TypeName);
            if (c) {
                arry.push({
                    TypeName: items[i].TypeName,
                    Data: new c.model(items[i].Data)
                })
            } else {
                console.log(_items[i].TypeName + "无法识别!")
                return false;
            }
        }
        return arry;
    },
    //处理证件类型与证件号码的关联数据
    process: function (items) {
        for (let i in items) {
            if (items[i].TypeName == 'IdNumber' && items[i].Data.Group != "") {
                var sib = items.filter(p => p.TypeName == "Select" && p.Data.Group == items[i].Data.Group);
                if (sib.length > 0) {
                    items[i].Data.IdType = sib[0].Data.Value.value || "身份证";
                }
            }
        }
        return items;
    },
    //通过表单类型名称来校验该对像的value数据是否合法
    verify: function (typeName, data) {
        var type = this.types[typeName].model;
        if (type) {
            var obj = new type(data);
            if (obj.verify) {
                return obj.verify();
            } else {
                return { state: true, msg: "" }
            }
        } else {
            return { state: false, msg: "找不到：[" + typeName + "]对像原型！" }
        }
    },
    //教验整个表单对像集合的所有表单项的value数据是否合法
    formVerify: function (items) {
        var errCount = 0;
        for (let i in items) {
            let item = items[i];
            if (item.Data.IsRender) {
                console.log(item)
                var res = this.verify(item.TypeName, item.Data)
                if (!res.state) {
                    item.Data.error = true;
                    item.Data.errMsg = res.msg;
                    errCount++;
                } else {
                    item.Data.error = false;
                    item.Data.errMsg = "验证通过！";
                }
            }
        }
        return errCount == 0;
    },
    //获取整个表单的数据值，并返回json对像
    getValue: function (items) {
        var obj = {};
        for (let i in items) {
            var type = items[i].Data;
            if (!type.NullValue) {
                if (type.IsRender) {
                    if (type.getValue) {
                        obj[type.Name] = type.getValue();
                    } else {
                        obj[type.Name] = type.Value;
                    }
                } else {
                    obj[type.Name] = 'lg-no-render';
                }
            }
            
        }
        return obj;
    },
    //将服务器返回的表单数据赋值到表单数组对应类型的value属性，原理是遍历表单集合中的各项，并找到其Data下Name值与data数据中相同的key
    setValue: function (items, data) {
        if (typeof items == "string") {
            items = this.toJson(items);
        }
        if (typeof data == "string") {
            data = JSON.parse(data);
        }
        for (let i in items) {
            var type = items[i].Data;
            if (!type.NullValue) {
                if (type.setValue) {
                    type.setValue(data);
                } else {
                    type.Value = data[type.Name]
                }
                if (type.Value == "lg-no-render") {
                    type.IsRender = false;
                    type.Value = "";
                } else {
                    type.IsRender = true;
                }
            }   
        }
        return items;
    },
    setValueByBase: function (items, data) {
        if (typeof items == "string") {
            items = this.toJson(items);
        }
        if (typeof data == "string") {
            data = JSON.parse(data);
        }
        for (let i in items) {
            var type = items[i].Data;
            if (!type.NullValue) {
                if (type.setValue) {
                    type.setValue(data);
                } else {
                    type.Value = data[type.Name]
                }
                if (type.Value == "lg-no-render") {
                    type.IsRender = false;
                    type.Value = "";
                } else {
                    type.IsRender = true;
                }
            }
        }
        return items;
    },
    //注册监听事件
    addEventListener: function () {
        window.removeEventListener("click", this.LgSelectOptionSwitch);
        window.addEventListener("click", this.LgSelectOptionSwitch);
    },
    //被监听的下拉选择事件
    LgSelectOptionSwitch: function (e) {
        var path = e.path || e.composedPath()
        var select = path.filter(p => p.className == "lg-form-select")[0] || null;
        if (select == null) {
            $(".lg-select-position").hide();
            // console.log("符合点击空白处关闭条件！")
        } else {
            if (path.filter(p => p.className == "lg-select-title").length > 0) {
                $(".lg-select-position").hide();
                $(select).find(".lg-select-position").show();
                //console.log("符合打开条件！")
            } else if (e.target.className.indexOf("option") > -1) {
                $(select).find(".lg-select-position").hide();
            }
        }
    }
}

export { freeForm }